package com.allen.webservice.jaxrs.service.impl;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.allen.webservice.jaxrs.config.AuthInterceptor;
import com.allen.webservice.jaxrs.domain.Student;
import com.allen.webservice.jaxrs.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.interceptor.InInterceptors;

import javax.jws.WebService;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@InInterceptors(classes = AuthInterceptor.class)
@WebService(name = "studentService", targetNamespace = "http://service.jaxrs.webservice.allen.com",
    endpointInterface = "com.allen.webservice.jaxrs.service.StudentService")
public class StudentServiceImpl implements StudentService {

    static final List<Student> list = new ArrayList<>();

    //xml schema
    public static final String XMLNS = "xmlns=\"http://www.cdisc.org/ns/odm/v1.3\"";
    public static final String XSI = "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
    public static final String DS = "xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"";
    public static final String SCHEMA_LOCATION = "xsi:schemaLocation=\"http://www.cdisc.org/ns/odm/v1.3 ODM1-3-2.xsd http://www.trialos.com/edc/ns/odm eCollect-ODM.xsd\"";


    static {
        Student student1 = new Student("张三", "男", 11);
        Student student2 = new Student("王红", "女", 12);
        list.add(student1);
        list.add(student2);
    }

    @Override
    public List<Student> getAllStudent() {
        return list;
    }

    @Override
    public Student findStudent(String stuName) {
        final Optional<Student> first = list.stream().filter(student -> student.getName().equals(stuName)).findFirst();
        return first.orElse(null);
    }


//    public String saveStudent() {
//         ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//         HttpServletRequest request = requestAttributes.getRequest();
//         HttpServletResponse response = requestAttributes.getResponse();
//        try {
//            //获取请求流数据
//            ServletInputStream inputStream = request.getInputStream();
//            String data = IoUtil.read(inputStream, Charset.defaultCharset());
//            log.info("请求的数据内容是：{}", data);
//            //需要把xml数据转化为对象  需要使用jabx技术
//             Student student = CxfUtils.jsonToObjectRemoveFlag(data, Student.class);
//             list.add(student);
//        } catch (Exception e) {
//           log.error("异常："+ ExceptionUtil.getMessage(e));
//        }
//        return "good";
//    }


//    前端传输xml格式会序列化为对象，对象使用了@XmlRootElement标记会自动转换
    @Override
    public String saveStudent(Student student) {
        try {
            list.add(student);
        } catch (Exception e) {
            log.error("异常："+ ExceptionUtil.getMessage(e));
        }
        return "good";
    }

}
